package com.jhc.drone.communication.network.udp;


import com.jhc.drone.communication.enums.ProtocolEnum;
import com.jhc.drone.communication.network.Gateway;
import com.jhc.drone.communication.network.cache.DroneCache;
import com.jhc.drone.communication.processor.MessageProcessor;
import com.jhc.drone.communication.processor.MessageProcessorFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.ReadTimeoutException;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lcp
 * @date 2024年12月2024/12/30 14:42
 * @describe
 */
@Slf4j
public class UdpClientInboundHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private final MessageProcessor messageProcessor;

    public UdpClientInboundHandler(MessageProcessorFactory processorFactory, ProtocolEnum protocolEnum) {
        this.messageProcessor = processorFactory.createMessageProcessor(protocolEnum);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
        log.error("exceptionCaught--------{}", ctx.channel().remoteAddress());
        if (throwable instanceof ReadTimeoutException) {
            log.error("udp会话已超时失效，很可能是对方非正常通出或网络故障，即将以会话异常的方式执行关闭流程 ...{}", ctx.channel().remoteAddress());
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("channelActive--------{}", ctx.channel().remoteAddress());
        super.channelActive(ctx);
        Gateway.setSocketType(ctx.channel(), Gateway.SOCKET_TYPE_UDP);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.warn("channelInactive--------{}", ctx.channel().remoteAddress());
        super.channelInactive(ctx);
        Gateway.removeSocketType(ctx.channel());
        DroneCache.deleteKey(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf bytebuf) throws Exception {

        messageProcessor.unpack(bytebuf, ctx.channel());
    }
}
